package com.xd.dubbo.globalTransaction.aspect;

import com.xd.dubbo.globalTransaction.annotation.GlobalTransactional;
import com.xd.dubbo.globalTransaction.transactional.GlobalTransaction;
import com.xd.dubbo.globalTransaction.transactional.GlobalTransactionalManager;
import com.xd.dubbo.globalTransaction.transactional.TransactionType;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class GlobalTransactionAspect implements Ordered {


    @Around("@annotation(com.xd.dubbo.globalTransaction.annotation.GlobalTransactional)")
    public void invoke(ProceedingJoinPoint point) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        GlobalTransactional globalTransactional = method.getAnnotation(GlobalTransactional.class);
        String groupId = "";
        if (globalTransactional.startTransactional()) {
            groupId = GlobalTransactionalManager.createGlobalTransactionGroup();
        } else {
            groupId = GlobalTransactionalManager.getCurrentGroupId();
        }
        groupId = "9729977f-5a3a-4d9d-a14d-7a8f678dcea0";

        GlobalTransaction globalTransaction = GlobalTransactionalManager.createGlobalTransaction(groupId);

        try {
            point.proceed();
            GlobalTransactionalManager.addGlobalTransaction(globalTransaction, globalTransactional.endTransactional(), TransactionType.commit);
        } catch (Exception e) {
            GlobalTransactionalManager.addGlobalTransaction(globalTransaction, globalTransactional.endTransactional(), TransactionType.rollback);
            e.printStackTrace();
        } catch (Throwable throwable) {
            GlobalTransactionalManager.addGlobalTransaction(globalTransaction, globalTransactional.endTransactional(), TransactionType.rollback);
            throwable.printStackTrace();
        }
    }


    @Override
    public int getOrder() {
        return 10000;
    }
}
